import java.awt.Canvas;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Level implements Serializable{
	private static final long serialVersionUID = 1L;
	int levelID;
	int breite;
	int hoehe;
	int leftlLevelID;
	int toplLevelID;
	int bottomlLevelID;
	int rightLevelID;
	Canvas parent;
	String dateiname;
	String standardFloor;
	String randomFloor;
	List<LevelObject> levelObjects;
	Tile[][] tiles;
	
	public Level(Canvas canvas)
	{
		levelObjects = new ArrayList<LevelObject>();
		parent = canvas;
	}
	
	public void saveLevel(String dateiname){
		try {
			ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(dateiname));
			os.writeObject(this);
			os.flush();
			os.close();
        	System.out.println("Welt gespeichert!");
		}
        catch(IOException e) {
        	System.out.println("Es ist ein Fehler beim Speichern aufgetreten.");
        }        
	}
	
	public void loadLevel(String dateiname) {
        if ((new File(dateiname)).exists()) {
        	try {
        		FileInputStream fs = new FileInputStream(dateiname);
                ObjectInputStream is = new ObjectInputStream(fs);
                Level temp =(Level)is.readObject();
                this.breite = temp.breite;
                this.hoehe = temp.hoehe;
                this.standardFloor = temp.standardFloor;
                this.randomFloor = temp.randomFloor;
                this.levelObjects = temp.levelObjects;
                this.tiles = temp.tiles;
                this.leftlLevelID = temp.leftlLevelID;
                this.rightLevelID = temp.rightLevelID;
                this.toplLevelID = temp.toplLevelID;
                this.bottomlLevelID = temp.bottomlLevelID;
                this.levelID = temp.levelID;
                
                for (LevelObject levelObject : levelObjects) {
        			for (int x = 0; x < levelObject.object.length; x++) {
        				for (int y = 0; y < levelObject.object[x].length; y++) {
        					Tile t = levelObject.object[x][y];
        					tiles[x + levelObject.startPositionX][y + levelObject.startPositionY] = t;
        				}
        			}
        		}

                is.close();
            }
            catch (Exception e) {
            	System.out.println("Fehler Junge! "+e.toString());
            }
        }
	}
}
